package com.jing.lock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号灯
 */
public class SemaphoreDemo{
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6 ; i++) {
            int finalI = i;
            new Thread(() -> {
                //获取信号
                try {
                    semaphore.acquire();
                    //停车
                    System.out.println(Thread.currentThread().getName() + "\t 当前第" + finalI + "辆车停入");
                    //离开
                    try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
                    System.out.println(Thread.currentThread().getName() + "\t 当前第" + finalI + "辆车离开");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放信号
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
